package cn.wolfcode.trip.app.controller;

import cn.wolfcode.trip.base.service.IUserService;
import cn.wolfcode.trip.base.util.JSONResult;
import cn.wolfcode.trip.base.util.UserContext;
import com.sun.org.apache.regexp.internal.RE;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 登录资源控制器
 */
@RequestMapping("/sessions")
@RestController
public class SessionController {

    @Autowired
    private IUserService userService;

    /**
     * 根据邮箱和密码查询是否有此用户
     * 如果有就把次用户放入jsonResult中返回给前台
     * 没有的话service会抛出异常
     * 返回异常信息
     * @param email
     * @param password
     * @return
     */
    @PostMapping
    public Object login(String email,String password){
        JSONResult jsonResult = new JSONResult();
        try {
            Object user = userService.login(email, password);
            jsonResult.setUser(user);
        } catch (Exception e) {
            jsonResult.mark(e.getMessage());
            e.printStackTrace();
        }
        return  jsonResult ;
    }

    /**
     * 退出登录
     * 销毁session
     */
    @DeleteMapping
    public void logout(){
        UserContext.getSession().invalidate();

    }

}
